<template>
  <div class="root">
    <!--工具条-->
    <div class="toolbar">
      <el-button type="primary">保存并新增</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
    <el-row>
      <el-col :span="12">
        单据日期:
        <el-date-picker type="date" placeholder="请选择单据日期" value-format="YYYY-MM-DD" size="small"
          v-model="shipmentForm.billDate" />
      </el-col>
      <el-col :span="12">
        单据编号:<el-input v-model="shipmentForm.code" style="width: 240px" placeholder="单据编号自动生成！" :disabled="true" />
      </el-col>
    </el-row>


    <div class="detail">
      <!--明细-->
      <div class="detail-title">
        <span>调拨明细</span>
        <el-button type="primary" size="small" @click="addRow">增行</el-button>
        <el-button type="primary" size="small" @click="delRow">删行</el-button>
      </div>
      <!--列表-->
      <el-table :data="tableData" style="width: 1100px" stripe border @cell-click="cellck" ref="purchaseRef">
        <el-table-column type="selection" width="50" header-algin="center" align="center" />
        <el-table-column type="index" label="序号" width="80" header-algin="center" align="center" />

        <el-table-column prop="goodsname" label="商品" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{ row.goodsname }}</span>
            <el-input v-else v-model="row.goodsname" placeholder="点击选择商品" @click="isshowchoose = true"></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="unit" label="单位" width="80" header-algin="center" align="center" />



        <el-table-column prop="num" label="数量" width="150" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.num
              }}</span>
            <el-input-number v-else v-model="row.num" size="small" :min="0"></el-input-number>
          </template>
        </el-table-column>



        <el-table-column prop="outName" label="调出仓库(批量)" width="180" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{ row.outName }}</span>
            <el-select v-else v-model="row.outName" clearable placeholder="请选择调出仓库"
              @click="getOutWarehouse(row.goodsId)">
              <el-option v-for="item in outWarehouse" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="inName" label="调入仓库(批量)" width="180" header-algin="center" align="center">
          <template v-slot="{ row, column }">

            <span v-if="row.show[column.property] == undefined">{{ row.inName }}</span>
            <el-select v-else v-model="row.inName" clearable placeholder="请选择调入仓库" @click="getInWarehouse()">
              <el-option v-for="item in inWarehouse" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="notes" label="备注" width="180" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{ row.notes }}</span>
            <el-input v-else v-model="row.notes" placeholder="请输入备注信息"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <!--  选择商品  -->
      <ChooseGoods :visible="isshowchoose" @choose="choose" @close="isshowchoose = false"></ChooseGoods>
      <div>
        <input type="text" placeholder="填写订单备注信息" class="note" v-model="shipmentForm.note" />
      </div>
    </div>
    <el-row style="margin-top: 20px">
      <el-col :span="6">制单人:<input type="text" class="ipt" v-model="shipmentForm.user" /></el-col>
      <el-col :span="6">审核人:<input type="text" class="ipt" v-model="shipmentForm.audit" /></el-col>

    </el-row>
  </div>
</template>

<script setup>

import { ref, onMounted } from 'vue'

import ChooseGoods from "@/views/set/goods/ChooseGoods.vue";
import { ElMessage } from "element-plus";
import { getUser } from "@/utils/session";
import { getWarehouseList, SaveAllocate, getAllocateById } from "@/api/warehouse/list.jsx";
import { useRoute } from 'vue-router'
//仓库数据
const outWarehouse = ref([])
const inWarehouse = ref([])

//表格数据
const tableData = ref([])
//初始化10行
function init() {
  for (let i = 1; i <= 4; i++) {
    addRow()
  }
}

const route = useRoute();
console.log(route);


function addRow() {
  tableData.value.push({
    goodsId: "",
    goodsname: "",
    unit: "",
    num: 0,
    outId: "",
    outName: "",
    inId: "",
    inName: "",
    notes: "",
    show: {}
  })
}


const shipmentForm = ref({
  billDate: '',
  code: '',
  note: '',
  user: '',
  audit: '',
  eid: getUser().eid
})

async function queryAllocateById(id) {
  let res = await getAllocateById(id);
  if (res.code == 200) {
    shipmentForm.value = res.data;
    //获取明细
    let tmp = res.data.allocateDetailList;
    //遍历明细 给每一个对象增加属性show={}
    tmp.forEach(el => {
      el.show = {};
    });
    tableData.value = tmp;
  }
}

//单元格双击事件
const lastRow = ref({})//记录上一次双击的是哪一行
function cellck(row, column) {
  //先清空之前添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }
  let tmp = column.property;
  row.show[tmp] = true;
  //记录双击的行
  lastRow.value = row;
}

//删除行
const purchaseRef = ref(null)//表格引用
function delRow() {
  let rows = purchaseRef.value.getSelectionRows()
  if (rows.length == 0) {
    ElMessage({
      message: "请选择要删除的行！",
      type: "warning"
    });
  }
  rows.forEach(r => {
    removeData(r)
  })
}

//从tableData移除行，r代表要移除的行
function removeData(r) {
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //获取当前行对象
    let tmp = tableData.value[i];
    //判断tmp是否是要删除的对象r
    if (tmp == r) {
      tableData.value.splice(i, 1);
      break;//中止循环
    }
  }
}


//商品选择
const isshowchoose = ref(false);//是否显示商品选择框
//选择商品
function choose(rows) {
  if (rows.length == 0) {
    return
  }
  //获取选择行的索引
  let index = -1;
  //遍历表格数据，查询选择的第一个对象的未知
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //临时对象
    let tmp = tableData.value[i];
    if (tmp == lastRow.value) {
      index = i;
      break;
    }
  }
  if (index == -1)
    return;
  //遍历选择的商品
  for (let i = 0, len = rows.length; i < len; i++) {
    //临时对象
    let obj = tableData.value[index];
    obj.goodsId = rows[i].id;
    obj.goodsname = rows[i].name;
    obj.unit = rows[i].unit;

    index++;
  }
  //先清空之前添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }
}




async function getInWarehouse() {
  let data = {
    eid: getUser().eid
  }
  let res = await getWarehouseList(data)
  if (res.code == 200) {

    inWarehouse.value = res.data
  }
}


//调出仓库
async function getOutWarehouse(goodsId) {
  console.log(isNumber(goodsId));
  let data = {
    eid: getUser().eid,
    goodsId: goodsId
  }

  if (!isNumber(goodsId)) {
    ElMessage({
      type: 'warning',
      message: '请选择商品',
    })
    return
  }
  let res = await getWarehouseList(data)
  if (res.code == 200) {
    outWarehouse.value = res.data
  }
}

function isNumber(value) {
  return !isNaN(parseFloat(value)) && isFinite(value);
}


//新增保存
async function save() {
  const detail = [];//保存用户填写的明细
  //便利表格数据
  tableData.value.forEach(r => {
    //判断当前对象中是否选择了商品 如果是，加入到明细
    if (r.goodsname != undefined && r.goodsname != "") {
      detail.push(r)
    }
  })
  if (detail.length == 0) {
    ElMessage({
      message: "调拨单明细不能为空!",
      type: "warning"
    })
    return
  }


  for (let i = 0; i < detail.length; i++) {
    if (detail[i].num == 0) {
      ElMessage({
        message: "数量不能为0!",
        type: "warning"
      })
      return
    }

    if (detail[i].outName == undefined || detail[i].outName == "") {
      ElMessage({
        message: "调出仓库不能为空!",
        type: "warning"
      })
      return
    }
    if (detail[i].inName == undefined || detail[i].inName == "") {
      ElMessage({
        message: "调入仓库不能为空!",
        type: "warning"
      })
      return
    }

  }




  //参数值
  let data = shipmentForm.value;//调拨单基本信息
  //将明细加入调拨单
  data.allocateDetailList = detail;
  //保存
  let res = await SaveAllocate(data);

  if (res.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    })
  }

}



onMounted(() => {
  init();
  queryAllocateById(route.params.id)
});

</script>

<style scoped lang="scss">
.toolbar {
  height: 40px;
  line-height: 40px;
  text-align: right;
  padding-right: 20px;
}

.root {
  border: #ebeef5 solid 1px;
  background-color: #fff;
  height: 100%;
  padding-left: 20px;
}

.toolbar {
  height: 40px;
  line-height: 40px;
  text-align: right;
  padding-right: 20px;
}

.detail {
  margin-right: 20px;
  margin-top: 30px;
  padding-left: 10px;
}

.detail-title {
  height: 40px;
  line-height: 40px;
  border: #ebeef5 solid 1px;
  border-bottom-style: none;
  padding-left: 10px;
}

.detail-title button {
  margin-left: 10px;
}

.note {
  width: 100%;
  border-style: none;
  outline-style: none;
  border-bottom: #ebeef5 solid 1px;
  margin-top: 20px;
}
</style>
